//
//  EasyButton.swift
//  HelloKitty
//
//  Created by HelloKitty on 15/7/2019.
//  Copyright © 2019 HelloKitty. All rights reserved.
//

import UIKit

class EasyButton: UIButton {
    /// UIButton默认图片在左,文字在右
    /// 带图片的话,整体宽度设置要至少大于两倍的图片宽高,否则会压缩变形
    /// 动态宽度
    enum Position {
        case top    /// 图片在上,垂直居中
        case left   /// 图片在左,水平居中
        case right  /// 图片在右,水平居中
        case bottom /// 图片在下,垂直居中
    }
    
    private var position: Position?
    private var space: CGFloat = 0
    
    convenience init(_ position: Position, at space: CGFloat = 0) {
        self.init(type: .custom)
        self.position = position
        self.space = space
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()

        let imageHeight = imageView?.intrinsicContentSize.height ?? 0
        let imageWidth = imageView?.intrinsicContentSize.width ?? 0
        let titleWidth = titleLabel?.intrinsicContentSize.width ?? 0
        let titleHeight = titleLabel?.intrinsicContentSize.height ?? 0
        if let position = position {
            switch position {
                case .top:
                    titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageWidth, bottom: -imageHeight - space/2, right: 0)
                    imageEdgeInsets = UIEdgeInsets(top: -titleHeight-space/2, left: 0, bottom: 0, right: -titleWidth)
                case .bottom:
                    titleEdgeInsets = UIEdgeInsets(top: -imageHeight-space/2, left: -imageWidth, bottom: 0, right: 0)
                    imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: -titleHeight-space/2, right: -titleWidth)
                case .left:
                    titleEdgeInsets = UIEdgeInsets(top: 0, left: space / 2.0, bottom: 0, right: -space / 2.0)
                    imageEdgeInsets = UIEdgeInsets(top: 0, left: -space / 2.0, bottom: 0, right: space / 2.0 )
                case .right:
                    titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageWidth - space/2.0, bottom: 0, right: imageWidth + space/2.0)
                    imageEdgeInsets = UIEdgeInsets(top: 0, left: titleWidth + space/2.0, bottom: 0, right: -titleWidth - space/2.0)
            }
        }
    }
}
